<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>深拷贝和浅拷贝</title>
  </head>
  <body>
    <script>
      function shallowCopy(obj) {
        //确保参数是普通对象和数组
        if (
          typeof obj !== 'object' ||
          obj === null ||
          obj.constructor === Date ||
          obj.constructor === RegExp
        ) {
          return obj
        }
        //根据传进来的类型，定义一个新的数组或者对象
        const newObj = obj.constructor === Object ? {} : []
        // 循环赋值
        for (let n in obj) {
          if (obj.hasOwnProperty(n)) {
            newObj[n] = obj[n]
          }
        }
        return newObj
      }

      function deepCopy(obj) {
        //确保参数是普通对象和数组
        if (typeof obj !== 'object' ||
          obj === null ||
          obj.constructor === Date ||
          obj.constructor === RegExp) {
          return obj
        }
        //instanceof 判断类型，必须先判断Array，因为[] instanceof Object 也返回true
        const newObj = obj instanceof Array ? [] : {}
        for (n in obj) {
          if (obj.hasOwnProperty(n)) {
            newObj[n] = obj[n] instanceof Object ? deepCopy(obj[n]) : obj[n]
          }
        }
        return newObj
      }
    </script>
  </body>
</html>
